const dbUser = require("../../db/db_user")();

/* 接收post请求 */
function parsePostData(ctx) {
  return new Promise((resolve, reject) => {
    try {
      let postdata = "";
      ctx.req.on("data", data => {
        postdata += data;
        // console.log(String(postdata));
      });
      ctx.req.addListener("end", function() {
        resolve(postdata);
      });
    } catch (error) {
      reject(error);
    }
  });
}

module.exports = function() {
  return async function(ctx, next) {
    // 允许来自所有域名请求
    ctx.set("Access-Control-Allow-Origin", "*");
    // 这样就能只允许 http://localhost:8080 这个域名的请求了
    // ctx.set("Access-Control-Allow-Origin", "http://localhost:8080");

    // 设置所允许的HTTP请求方法
    ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");

    // 字段是必需的。它也是一个逗号分隔的字符串，表明服务器支持的所有头信息字段.
    ctx.set(
      "Access-Control-Allow-Headers",
      "x-requested-with, accept, origin, content-type"
    );
    ctx.set("content-type", "application/json; charset=UTF-8");

    // let isExist = await parsePostData(ctx).then(postData=>{
    //   postData = JSON.parse(postData)
    //   return dbUser.findUserName(postData.userName)
    // }).then(result=>{
    //   return result ? false : dbUser.add(postData);
    // }).then(result =>{
    //   return result;
    // });
    // console.log(isExist);
    let isExist = await parsePostData(ctx).then(async postData => {
      postData = JSON.parse(postData);
      let findResult = await dbUser
        .findUserName(postData.userName)
        .then(result => {
          return result;
        });
        return findResult ? false : dbUser.addUser(postData);
    }).then(result=>{
      // console.log(result)
      return result;
    });
    let result =  isExist ? isExist.n :'用户名已被注册';

    ctx.body = { 'result': result };
  };
};
